//
//  PlaceholderTextView.m
//  OSChina
//
//  Created by 8b410-2 on 17/1/5.
//  Copyright © 2017年 abb. All rights reserved.
//

#import "PlaceholderTextView.h"

static NSString * const kTextKey = @"text";

@interface PlaceholderTextView ()

@property (nonatomic, strong) UILabel *placeholderView;

@end

@implementation PlaceholderTextView
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self setupPlaceholderView];
    }
    return self;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        [self setupPlaceholderView];
    }
    return self;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self removeObserver:self forKeyPath:kTextKey];
}

- (void)setupPlaceholderView {
    _placeholderView = [UILabel new];
    _placeholderView.userInteractionEnabled = NO;
    _placeholderView.font = self.font;
    _placeholderView.textColor = [UIColor colorWithHex:0xc8c8ce];
    _placeholderView.backgroundColor = [UIColor clearColor];
    [self addSubview:_placeholderView];
    [_placeholderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).offset(8);
        make.left.equalTo(self).offset(5);
    }];
    
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(textDidChange:)
                          name:UITextViewTextDidChangeNotification object:self];
    
    [self addObserver:self forKeyPath:kTextKey options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:kTextKey]) {
        _placeholderView.hidden = [self hasText];
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)textDidChange:(NSNotification *)notification {
    _placeholderView.hidden = [self hasText];
}
#pragma mark - setter

- (void)setFont:(UIFont *)font {
    [super setFont:font];
    _placeholderView.font = font;
}

- (void)setTextAlignment:(NSTextAlignment)textAlignment {
    [super setTextAlignment:textAlignment];
    _placeholderView.textAlignment = textAlignment;
}

#pragma mark placeholder

- (void)setPlaceholder:(NSString *)placeholder {
    _placeholderView.text = placeholder;
}

- (NSString *)placeholder {
    return _placeholderView.text;
}

@end
